package org.bdware.irs.backend.servicesImpl;

import com.google.gson.Gson;
import com.nimbusds.jose.jwk.JWK;
import org.apache.log4j.Logger;
import org.bdware.irp.client.IrpClientImpl;
import org.bdware.irp.exception.IrpClientException;
import org.bdware.irp.irplib.util.GlobalUtils;
import org.bdware.irp.stateinfo.StateInfoBase;
import org.bdware.irp.stateinfo.UserStateInfo;
import org.bdware.irs.IrsBootWithTcp;
import org.bdware.irs.backend.services.IrsService;
import org.bdware.irs.server.http.IrsHandler;
import org.bdware.irs.server.http.IrsMain;
import org.rocksdb.RocksDBException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

/*
通过irpclient和irs进行通信,部分功能为实现，需要增加一些新的操作
 */
public class IrsServiceRemoteImpl implements IrsService {

    Logger logger = Logger.getLogger(IrsServiceRemoteImpl.class);


    public IrpClientImpl client;
    public String url;

    public IrsServiceRemoteImpl() throws InterruptedException {
        try{
            JWK jwk = GlobalUtils.loadKeysFromJWKFile("./keys/jwk/dou.TEST.jwk");
            logger.info("load the jwk finish");
            url = "tcp://"+ IrsBootWithTcp.irsConfig.irsAddress+":" + IrsBootWithTcp.irsConfig.tcpPort;
            client = new IrpClientImpl(jwk, "irs_client_"+ IrsBootWithTcp.irsConfig.prefix, url);
            client.connect(url);
        }catch(Exception e){
            e.printStackTrace();
        }

    }

    @Override
    public StateInfoBase resolve(String  doi){
        StateInfoBase saveStateInfo = null;
        try {
            saveStateInfo = client.resolve(doi);
        } catch (IrpClientException e) {
            e.printStackTrace();
        }
        return saveStateInfo;
    }
    @Override
    public boolean registerUser(UserStateInfo userStateInfo){
        return false;
    }
    @Override
    public boolean updateUser(UserStateInfo userStateInfo ){
        return true;
    }
    @Override
    public UserStateInfo getCurrentUser(String doi){
        StateInfoBase saveStateInfo = null;
        try {
            saveStateInfo = client.resolve(doi);
        } catch (IrpClientException e) {
            e.printStackTrace();
        }
        if(saveStateInfo == null)
            return null;
        UserStateInfo userStateInfo = UserStateInfo.fromStateInfoBase(saveStateInfo);
        return userStateInfo;
    }
    @Override
    public List getBindedRepoAndRegs(){
        return null;
    }
    @Override
    public Set getAllUsers(){
        return null;
    }
    @Override
    public List getAllStateInfos(){
        return null;
    }

    @Override
    public boolean isManager(String doi, String role){
        return true;
    }

    @Override
    public String getValue(String key){
        return null;
    }




}
